<?php
	class Controller_Report extends Controller_Abstract {
		function actionIndex(){
			ini_set('memory_limit', '2048M');
			set_time_limit(600);
			
			if($this->_context->isGET()){
				$this->_view['reporttype'] = $this->_context->get('reporttype', 0);
				$this->_view['duration'] = $this->_context->get('duration', 0);
				$this->_view['customrangedate'] = ($this->_view['duration'] == 4)? array('start' => $this->_context->startdate, 'end' => $this->_context->enddate) : array();
				$this->_view['interval'] = $this->_context->get('interval', 0);
				$this->_view['displayCols'] = $this->_context->get('displaycol', array());
				if($this->_view['reporttype'] == '3'){
					$this->_view['displayCols']['7'] = '7';
				}
				
				if($this->_context->submit == "Generate Report"){
					$page = $this->_context->get('page', 1);
					
					$this->_view['reportItems'] = $this->getReport($this->_view['reporttype'], $this->_view['duration'], $this->_view['customrangedate'], $this->_view['interval'], $this->_view['displayCols'], $page);
					if(isset($this->_view['reportItems']['totalCount'])){
						$pagination = new Pagination($this->_view['reportItems']['totalCount'], $this->_context->requestUri(), $page);
						unset($this->_view['reportItems']['totalCount']);
						$this->_view['pagination'] = $pagination->render();						
					}
					$this->_view['filters'] = $this->getFiltersFromreportItems($this->_view['reportItems'], $this->_view['reporttype'], $this->_view['displayCols']);
				}else if($this->_context->submit == "Export Report Csv"){
					$this->CsvDown($this->_view['reporttype'], $this->_view['duration'], $this->_view['customrangedate'], $this->_view['interval'], $this->_view['displayCols']);
				}
			}
		}
		
		function actionGetuserpixel(){
			if($this->_context->isGET()){
				$cam = $this->_context->get('camval', '');
				$pub = $this->_context->get('pubval', '');
				$pla = $this->_context->get('plaval', '');
				$report = new Report();
				
				$params = array();
				if($cam != ''){
					$params['cam'] = $cam;
				}
				if($pub != ''){
					$params['pub'] = $pub;
				}
				if($pla != ''){
					$params['pla'] = $pla;
				}
				
				if($cam == ''){
					$cam = $report->getCol('cam', $params);
				}
				if($pub == ''){
					$pub = $report->getCol('pub', $params);
				}
				if($pla ==  ''){
					$pla = $report->getCol('pla', $params);
				}

				return json_encode(array('cam'=>$cam, 'pub'=>$pub, 'pla'=>$pla));
			}
		}
		
		private function getReport($reportType, $duration, $customrangedate, $interval, $displayCols, $page=1){
			$report = new Report();
			if($reportType == 0){
				$reportItems = $report->getMediaReport($duration, $customrangedate, $interval, $displayCols);
			}else if($reportType == 1){
				$reportItems = $report->getSiteReport($duration, $customrangedate, $interval, $displayCols, $page);
			}else if($reportType == 2){
				$reportItems = $report->getGameReport($duration, $customrangedate, $interval, $displayCols);
			}else if($reportType == 3){
				$reportItems = $report->getAdvertiserReport($duration, $customrangedate, $interval, $displayCols);
			}else if($reportType == 4){
				$reportItems = $report->getShareReport($duration, $customrangedate, $interval, $displayCols);
			}else if($reportType == 5){
				$reportItems = $report->getEmailReport($duration, $customrangedate, $interval, $displayCols);
			}else if($reportType == 6){
				$reportItems = $report->getOfferOfWeekReport($duration, $customrangedate, $interval, $displayCols);
			}else if($reportType == 7){
				$reportItems = $report->getBluebarOfferReport($duration, $customrangedate, $interval, $displayCols);
			}else if($reportType == 8){
				$reportItems = $report->getOptinReport($duration, $customrangedate, $interval, $displayCols);
			}else if($reportType == 9){
				$reportItems = $report->getBannerOfferReport($duration, $customrangedate, $interval, $displayCols);
			}else if($reportType == 10){
				$reportItems = $report->getDailyDealsOfferReport($duration, $customrangedate, $interval, $displayCols);
			}
			return $reportItems;
		}
		
		private function getFiltersFromreportItems($reportItems, $reportType, $displayCols)
		{
			$filters = array();	
			if(!empty($reportItems)){
				$cols=array('buy_type', 'media_type', 'pub', 'pla', 'cam', 'cre', 'monetization', 'site');
				
				foreach ($reportItems as $reportItem) {
					if($reportType == 3){
						foreach($reportItem as $r){
							foreach ($displayCols as $col) {
								$filters[$cols[$col]][] = $r[$cols[$col]];
							}
						}
					}else{
						foreach ($displayCols as $col) {
							$filters[$cols[$col]][] = $reportItem[$cols[$col]];
						}
					}
				}
				foreach ($displayCols as $col) {
					if(is_array($filters[$cols[$col]])){
						$filters[$cols[$col]] = array_unique($filters[$cols[$col]]);
						array_multisort($filters[$cols[$col]], SORT_ASC, SORT_STRING);
					}
				}
			}
			
			return $filters;
		}
			
		private function CsvDown($reportType, $duration, $customrangeDate, $interval, $displayCols){
			$reportItems = $this->getReport($reportType, $duration, $customrangeDate, $interval, $displayCols, 0);
			if($reportType == 0){
				$cols = array('Buy Type', 'Publisher Type', 'Publisher', 'Placement', 'Campaign', 'Creative', 'Monetization', 'Site');
				$csvHeader[] = "Date";
				foreach($displayCols as $val){
					$csvHeader[] = $cols[$val];
				}
				$cols = array('Impressions', 'Clicks', 'CTR %', 'CPC', 'Leads', 'Paid Conversion', 'Actual Conversions', 'Scrub Rate', 'CPL', 
							  'Conversion %', 'Revenue($)', 'Cost($)', 'Gross Profit($)', 'GM', 'ROAS', 'CPM', 'RPM', 'RPC', 'RPL');
				foreach($cols as $col){
					$csvHeader[] = $col;
				}
				$cols = array('buy_type', 'media_type', 'pub', 'pla', 'cam', 'cre', 'monetization', 'site');
				foreach($reportItems as $key=>$data){
					list($date['start'], $site) = explode('|', $data['date']);
					if($interval == 2){
						list($year, $week) = str_split($date['start'], 4);
						$date = Util::getStartAndEndDate($week, $year);
					}
					$csvDatas[$key]['t'] = $date['start'];
					if($interval==2){ $csvDatas[$key]['t'] .= '---'.$date['end'];}
					foreach($displayCols as $val){
						$csvDatas[$key][$cols[$val]] = $data[$cols[$val]];
					}
					$csvDatas[$key]['impression'] = $data['impression'];
					$csvDatas[$key]['click'] = $data['click'];
					$csvDatas[$key]['ctr_percentage'] = Util::divide($data['click'], $data['impression'], 2, true);
					$csvDatas[$key]['CPC'] = Util::divide($data['cost'], $data['click'], 2);
					$csvDatas[$key]['leads'] = $data['leads'];
					$csvDatas[$key]['paidconversion'] = $data['conversion'];
					$csvDatas[$key]['actualconversion'] = $data['conversion'] + $data['suppress'];
					$csvDatas[$key]['scrubrate'] = 1 - Util::divide($data['conversion'], ($data['conversion'] + $data['suppress']), 2);
					$csvDatas[$key]['CPL'] = Util::divide($data['cost'], $data['leads'], 2);
					$csvDatas[$key]['conversion_percentage'] = Util::divide($data['leads'], $data['click'], 2, true);
					$csvDatas[$key]['revenue'] = $data['revenue'];
					$csvDatas[$key]['cost'] = $data['cost'];
					$csvDatas[$key]['grossProfit'] = $data['revenue'] - $data['cost'];
					$csvDatas[$key]['GM'] = Util::divide($csvDatas[$key]['grossProfit'] * 100, $data['revenue'],  2, true);
					$csvDatas[$key]['ROAS'] = Util::divide($csvDatas[$key]['grossProfit'], $data['cost'], 2, true);
					$csvDatas[$key]['CPM'] = Util::divide($data['cost'] * 1000, $data['impression'], 2);
					$csvDatas[$key]['RPM'] = Util::divide($data['revenue'] * 1000, $data['impression'], 2);
					$csvDatas[$key]['RPC'] = Util::divide($data['revenue'], $data['click'], 2);
					$csvDatas[$key]['RPL'] = Util::divide($data['revenue'], $data['lead'], 2);
				}
				$csvName = "Media Report";
				$this->sendCsv($csvDatas, $csvHeader, $csvName);
			}else if($reportType == 1){
				$cols = array('Buy Type', 'Publisher Type', 'Publisher', 'Placement', 'Campaign', 'Creative', 'Monetization', 'Site');
				$csvHeader[] = "Date";
				foreach($displayCols as $val){
					$csvHeader[] = $cols[$val];
				}
				$cols = array('Landing', 'Short Leads', 'Short Leads %', 'Short Reg Coreg', 'Short Reg Coreg %', 'Long Leads', 'Long Leads %', 
							  'Long Reg Coreg', 'Long Reg Coreg %', 'Update Profile', 'Update Profit Coreg', 'Update Profile Coreg %', 'Confirmed', 
							  'Confirmed %', 'Confirmed Coreg', 'Confirmed Coreg %', 'Daily Coreg Start', 'Daily Coreg End', 'Daily Coreg %', 
							  'Offer Completed', 'Offer / User', 'Tokens Rewarded', 'Tokens / User');
				foreach($cols as $col){
					$csvHeader[] = $col;
				}
				
				$cols = array('buy_type', 'media_type', 'pub', 'pla', 'cam', 'cre', 'monetization', 'site');
				foreach($reportItems as $key=>$data){
					$date['start'] = $data['date'];
					if($interval == 2){
						list($year, $week) = str_split($data['date'], 4);
						$date = Util::getStartAndEndDate($week, $year);
					}
					$csvDatas[$key]['t'] = $date['start'];
					if($interval==2){ $csvDatas[$key]['t'] .= '---'.$date['end'];}
					foreach($displayCols as $val){
						$csvDatas[$key][$cols[$val]] = $data[$cols[$val]];
					}
					$csvDatas[$key]['landing'] = $data['landing'];
					$csvDatas[$key]['basic_reg'] = $data['basic_reg'];
					$csvDatas[$key]['col_short_percentage'] = Util::divide($data['basic_reg'], $data['landing'], 2, true);
					$csvDatas[$key]['basic_reg_coreg'] = $data['basic_reg_coreg'];
					$csvDatas[$key]['basic_reg_coreg_percentage'] = Util::divide($data['basic_reg_coreg'], $data['basic_reg'], 2, true);
					$csvDatas[$key]['full_reg'] = $data['full_reg'];
					$csvDatas[$key]['full_reg_percentage'] = Util::divide($data['full_reg'], $data['basic_reg'], 2, true);
					$csvDatas[$key]['full_reg_coreg'] = $data['full_reg_coreg'];
					$csvDatas[$key]['full_reg_coreg_percentage'] = Util::divide($data['full_reg_coreg'], $data['full_reg'], 2, true);
					$csvDatas[$key]['profiling_coreg_start'] = $data['profiling_coreg_start'];
					$csvDatas[$key]['profiling_coreg_end'] = $data['profiling_coreg_end'];
					$csvDatas[$key]['col_coupdate_percentage'] = Util::divide($data['profiling_coreg_end'], $data['profiling_coreg_start'], 2, true);
					$csvDatas[$key]['confirmed'] = $data['confirmed_coreg'];
					$csvDatas[$key]['confirmed_percentage'] = Util::divide($data['confirmed_coreg'], $data['basic_reg'], 2, true);
					$csvDatas[$key]['confirmed_coreg'] = $data['confirmed'];
					$csvDatas[$key]['confirmed_coreg_percentage'] .= Util::divide($data['confirmed'], $data['confirmed_coreg'], 2, true);
					$csvDatas[$key]['daily_coreg'] = $data['daily_coreg'];
					$csvDatas[$key]['daily_coreg_'] = $data['daily_coreg'];
					$csvDatas[$key]['col_co_percentage'] = Util::divide($data['daily_coreg'], $data['daily_coreg'], 2, true);
					$csvDatas[$key]['reward'] = $data['reward'];
					$csvDatas[$key]['col_offer-user'] = Util::divide($data['reward'], $data['basic_reg'], 2, true);
					$csvDatas[$key]['token'] = $data['token'];
					$csvDatas[$key]['token-user'] = Util::divide($data['token'], $data['basic_reg'], 2, true);
				}
				$csvName = "Site Report";
				$this->sendCsv($csvDatas, $csvHeader, $csvName);
			}else if($reportType == 2){
				$csvHeader = array('Date', 'Site', 'Home View', 'More Credit View', 'Free Credit', 'User Play', 'Avg User Play', 'Variance of User Play', 
							  'Won($)', 'Expected Win Rate', 'Expected Value per Token', 'Variance Value per Token', 'Average Won', 'Credit Won', 
							  'Offer Completed', 'Avg Offer Completed', 'Avg Offer $', 'Tokens Rewarded', 'Avg Token Value');
				foreach($reportItems as $key=>$data){
					$date['start'] = $data['date'];
					if($interval == 2){
						list($year, $week) = str_split($data['date'], 4);
						$date = Util::getStartAndEndDate($week, $year);
					}
					
					$csvDatas[$key]['t'] = $date['start'];
					if($interval==2){ $csvDatas[$key]['t'] .= '---'.$date['end'];}
					$csvDatas[$key]['site'] = $data['site'];
					$csvDatas[$key]['homeview'] = $data['homeview'];
					$csvDatas[$key]['morecredit'] = $data['morecredit'];
					$csvDatas[$key]['free'] = $data['free'];
					$csvDatas[$key]['played'] = Util::divide($data['basic_reg_coreg'], $data['basic_reg'], 2, true);
					$csvDatas[$key]['Avg User Play'] = '';
					$csvDatas[$key]['Variance of User Play'] = '';
					$csvDatas[$key]['won'] = $data['won'];
					$csvDatas[$key]['Expected Win Rate'] = '';
					$csvDatas[$key]['Expected Value per Token'] = '';
					$csvDatas[$key]['Variance Value per Token'] = '';
					$csvDatas[$key]['Average Won'] = '';
					$csvDatas[$key]['credit'] = $data['credit'];
					$csvDatas[$key]['offer'] = $data['offer'];
					$csvDatas[$key]['Avg Offer Completed'] = '';
					$csvDatas[$key]['Avg Offer $'] = '';
					$csvDatas[$key]['token'] = $data['token'];
					$csvDatas[$key]['Avg Token Value'] = '';
				}
				$csvName = "Game Report";
				$this->sendCsv($csvDatas, $csvHeader, $csvName);
			}else if($reportType == 8){
				$csvHeader = array('Date', 'Site', 'Publisher', 'Placement', 'Campaign', 'Partner', 'Successed');
				foreach($reportItems as $key=>$data){
					$date['start'] = $data['date'];
					if($interval == 2){
						list($year, $week) = str_split($data['date'], 4);
						$date = Util::getStartAndEndDate($week, $year);
					}
					
					$csvDatas[$key]['t'] = $date['start'];
					if($interval==2){ $csvDatas[$key]['t'] .= '---'.$date['end'];}
					$csvDatas[$key]['domain'] = $data['domain'];
					$csvDatas[$key]['publisher'] = $data['pub'];
					$csvDatas[$key]['placement'] = $data['pla'];
					$csvDatas[$key]['campaign'] = $data['cam'];
					$csvDatas[$key]['partner'] = $data['partner'];
					$csvDatas[$key]['successed'] = $data['successed'];
				}
				$csvName = "Optin Report";
				$this->sendCsv($csvDatas, $csvHeader, $csvName);
			}
		}
		
		
		
		private function sendCsv($data, $headers, $filename) {
			
			header('Content-Type: application/csv');
			header('Content-Disposition: attachment; filename="' . $filename . '"');
			$output = fopen('php://output', 'w');
			fputcsv($output, $headers);
			if(!empty($data)){
				foreach ($data as $row) {
					fputcsv($output, $row);
				}			
			}

			
			fclose($output);
			exit;
		}
	}